
/*
 * @Author: 简佳成
 * @Date: 2019-12-18 11:02:00
 * @LastEditTime : 2020-02-07 13:17:39
 * @LastEditors  : Please set LastEditors
 * @Description: 签章图片上传成功后裁剪旋转角度控制页面
 * @FilePath: \Electronic_Seal_Mobile\src\pages\EditImg\index.js
 */

import React, { Component } from 'react';
import { connect, fetch } from 'dva';
import { Toast, Modal, List, Button, WhiteSpace } from 'antd-mobile';
import { createForm } from 'rc-form';
import router from 'umi/router';
import Cropper from 'react-cropper';
import RotaryScale from 'components/rotary-scale/index';
import DropDown from 'components/drop-down/index';
import styles from './index.less';
import { sealSizeType, ENTER_TYPE } from 'utils/Enum.js';
import 'cropperjs/dist/cropper.css'; // see installation section above for versions of NPM older than 3.0.0

@connect(({ upImgModel, loading }) => ({
  upImgModel,
}))
class CropperImg extends Component {
  constructor(props) {
    super(props);
    const {
      location: { params },
    } = props;
    const formValue = params ? params.formValue : {};
    this.ordAngel = 0; // 比较旋转角度
    this.state = {
      option: formValue.size ? formValue.size[0] : sealSizeType[0].value,
      baseData: '',
      reCorp: false,
      modal: false,
    };
    this.OnceOnlyTrigger = true;
    this.isInit = true;
  }

  _crop() {
    console.log('废弃方法');
    // image in dataUrl
    // .log(this.cropper.getCroppedCanvas().toDataURL());
  }

  /**
   * @description 取消按钮触发 图片不做更改
   */
  handleCancel = () => {
    const {
      location: { query },
    } = this.props;
    const {
      location: { params },
    } = this.props;
    router.replace({
      pathname: '/UploadImg',
      query: query,
      params: {
        ...params,
        //fileData: { url: '' }, 返回是否置空图片
      },
    });
  };

  /**
   * @description 点击确定执行的函数
   * @params 路由传递来的参数
   * @formValue 表单数据 需要合并
   * @x 图片长度
   * @y 图片高度
   * @mmPX 一毫米等于多少PX
   * @croppedBaseData 图片base64编码
   * @fileData 用于传递编码的字段
   */
  handleUpLoadImg = () => {
    const {
      location: { params, query },
    } = this.props;
    const { option, baseData } = this.state;
    if (params.formValue) {
      params.formValue.size = [option];
    }
    const [x, y] = option.split('x');
    // 毫米作为单位
    const mmPX = this.mm.getBoundingClientRect().width;
    const croppedBaseData = this.cropper
      .getCroppedCanvas({
        width: mmPX * x,
        height: mmPX * y,
      })
      .toDataURL();
    router.replace({
      pathname: '/UploadImg',
      query: query,
      params: {
        ...params,
        fileData: { url: croppedBaseData },
        baseData: baseData,
      },
    });

    /*
    // blob类型的数据发送
    this.cropper.getCroppedCanvas().toBlob(blob => {
      const formData = new FormData();
      formData.append('file', blob);
      .log(formData.get('file'))
      router.push({
        pathname: '/UploadImg',
        params: {
          fileData: formData.get('file').fileData,
        }
      })
      //fetch('/api/upload', { method: 'POST', body: formData });
    }); */
  };

  /**
   * @description 重置图片为初始状态
   */
  handleRestore = () => {
    const {
      location: {
        params: { restoreData },
      },
    } = this.props;
    const {
      upImgModel: { defaultImg },
    } = this.props;
    this.setState({
      modal: false,
      baseData: defaultImg,
      reCorp: false,
    });
  };

  handleClose = () => {
    this.setState({
      modal: false,
    });
  };

  handleOpen = () => {
    this.setState({
      modal: true,
    });
  };

  /**
   * @description 只触发一次的方法
   */
  handleOnceOnlyTrigger = () => {
    if (this.OnceOnlyTrigger) {
      this.OnceOnlyTrigger = false;
      this.setState({
        reCorp: false,
      });
    }
  };

  /**
   * @description 获取图片base64用以展示
   * @memberof CropperImg
   * @baseData 前面上传的图片base64
   */
  componentDidMount() {
    try {
      const {
        location: {
          params: {
            fileData: { url: baseData },
            reCorp,
          },
        },
      } = this.props;
      this.setState({
        baseData: baseData,
        rotaryData: baseData,
        reCorp: reCorp,
      });
    } catch (error) {
      Toast.fail('请先上传图片');
      router.push('./UploadImg');
    }
    // 注册一个监听裁剪的事件
    this.cropper.img.addEventListener('crop', event => {
      // 排除第一次初始化
      if (this.isInit) {
        this.isInit = false;
      } else {
        // 只要有裁剪就将复原->完成  并且只允许触发一次
        this.handleOnceOnlyTrigger();
      }
    });
  }

  /**
   * @description 印章大小选择项改变
   * @param {*} res 组件的回调参数
   */
  handleDropDownChange = res => {
    this.setState({
      option: res,
    });
  };

  /**
   * @description 控制图形旋转
   * @param {*} angle 下层传递上来的旋转角度
   */
  rotationAngle = angle => {
    const rotaAngle = angle - this.ordAngel;
    // .log(rotaAngle);
    this.cropper.rotate(rotaAngle);
    this.ordAngel = angle;
  };

  // 绕中心旋转canvas一定角度，图片大了效率过低 废弃
  /*   rotationAngle = angle => {
    .log(12312312312)
    const { baseData, rotaryData } = this.state;
    new Promise(resolve => {
      var img = new Image();
      img.src = rotaryData;
      img.onload = () => {
        resolve(img);
      };
    }).then(img => {
      var canvas = document.createElement('canvas'); //创建canvas元素
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      ctx.translate(img.width / 2, img.height / 2);
      ctx.rotate((angle * Math.PI) / 180); //旋转47度
      ctx.translate(-img.width / 2, -img.height / 2);
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const baseData = canvas.toDataURL();
      this.setState({
        baseData: baseData,
      });
    });
  }; */

  render() {
    const { baseData, option, reCorp, modal } = this.state;
    const [x, y] = option.split('x');
    return (
      <div className={styles.editImg}>
        <div style={{ width: '1mm', height: 0 }} ref={mm => (this.mm = mm)}></div>
        <div
          style={{
            height: '10vh',
            width: '100vw',
            display: 'flex',
            alignItems: 'center',
            background: 'rgba(3,5,8,1)',
            color: 'white',
            position:'relative'
          }}
        >
          <DropDown
            title="印章尺寸:"
            data={sealSizeType}
            unit="mm"
            value={option}
            onChange={this.handleDropDownChange}
          />
          <div className={styles.prompt}>沿着印章边缘裁剪，减少空白无效区域</div>
        </div>

        <Cropper
          ref={cropper => (this.cropper = cropper)}
          src={baseData}
          viewMode={1} //定义cropper的视图模式
          zoomable={true} //是否允许放大图像
          movable={true}
          guides={true} //显示在裁剪框上方的虚线
          background={false} //是否显示背景的马赛克
          rotatable={true} //是否旋转
          style={{ height: '65vh', width: '100%' }}
          cropBoxResizable={true} //是否可以拖拽
          cropBoxMovable={true} //是否可以移动裁剪框
          dragMode="move"
          center={true}
          modal={true} //默认true,是否在剪裁框上显示黑色的模态窗口。
          aspectRatio={x / y}
          autoCrop={true}
          onChange={() => {
            console.log(12312312);
          }}
          crop={() => {
            this._crop;
          }}
        />
        <RotaryScale
          startValue={0}
          maxScale={180}
          minScale={-180}
          color="white"
          background="rgba(0,0,0,0.8)"
          height={Math.ceil((document.documentElement.clientHeight / 100) * 14)}
          width={document.documentElement.clientWidth}
          onChange={res => {
            this.rotationAngle(res);
          }}
        />
        <div
          style={{
            background: 'rgba(0,0,0,0.8)',
            width: '100vw',
            height: '5vh',
          }}
        ></div>
        <div
          style={{
            position: 'fixed',
            bottom: 0,
            background: 'rgba(3,5,8,1)',
            width: '100vw',
            height: '7vh',
            display: 'flex',
            justifyContent: 'space-between',
          }}
        >
          <div
            inline
            onClick={this.handleCancel}
            className={styles.flex}
            style={{ background: 'rgba(3,5,8,1)', color: 'white', width: '25vw' }}
          >
            <a style={{ color: 'white' }}>取消</a>
          </div>

          {reCorp ? (
            <div
              inline
              onClick={this.handleOpen}
              className={styles.flex}
              style={{ background: 'rgba(3,5,8,1)', color: 'white', width: '25vw' }}
            >
              <a>复原</a>
            </div>
          ) : (
            <div
              inline
              onClick={this.handleUpLoadImg}
              className={styles.flex}
              style={{ background: 'rgba(3,5,8,1)', color: 'white', width: '25vw' }}
            >
              <a>完成</a>
            </div>
          )}
        </div>
        <Modal popup visible={this.state.modal} onClose={this.handleClose} animationType="slide-up">
          <List
            renderHeader={() => (
              <div>"恢复到原始状态"会移除对这张图片所做的编辑，此操作不可撤销</div>
            )}
            className="popup-list"
          >
            <List.Item>
              <Button onClick={this.handleRestore}>恢复到原始状态</Button>
              <WhiteSpace />
              <Button onClick={this.handleClose}>取消</Button>
            </List.Item>
          </List>
        </Modal>
      </div>
    );
  }
}
export default CropperImg;
